require 'baidu_map'

class Shop < ApplicationRecord
  enum state: [:pending, :opening, :closedown, :stop]
  enum business_range: [:province, :city, :district]

  mount_uploader :avatar, BaseUploader
  mount_uploader :big_avatar, BaseUploader
  mount_uploader :idcard_front, BaseUploader
  mount_uploader :idcard_back, BaseUploader
  mount_uploader :license, BaseUploader
  
  acts_as_mappable :distance_field_name => :distance,
                   :lat_column_name => :latitude,
                   :lng_column_name => :longitude

  has_many :shopers, dependent: :destroy
  has_many :spus, dependent: :destroy
  has_many :orders
  has_many :shop_notifications, dependent: :destroy
  scope :unread_shop_notifications, -> { where(:read_at => nil)}
  has_many :favorites, as: :favoriteable, dependent: :destroy
  has_many :coupons, dependent: :destroy
  has_many :settles, dependent: :destroy
  has_many :fare_templates, dependent: :destroy
  has_many :shop_chats, dependent: :destroy
  has_many :chat_users, through: :shop_chats
  has_many :spu_categories, dependent: :destroy

  belongs_to :province, optional: true
  belongs_to :city, optional: true
  belongs_to :district, optional: true
  belongs_to :shop_type, optional: true
  belongs_to :user, optional: true

  validates :name, presence: true, uniqueness: true, length: {maximum: 50}
  validates :phone, presence: true, uniqueness: true, length: {maximum: 50}

  def is_favorited?(user_id)
    favorite = Favorite.where(favoriteable_type: 'Shop', favoriteable_id: self.id, user_id: user_id).first
    !favorite.blank?
  end

  after_save :update_geo
  def update_geo
    address = self.full_address
    if address != ''
      location = BaiduMap.geocoder(address)
      self.update_columns(longitude: location["lng"], latitude: location["lat"])
    end
  end

  def full_address
    if self.province.blank? || self.city.blank? || self.district.blank?
      ""
    else
      "#{self.province.name}#{self.city.name}#{self.district.name}#{self.address}"
    end
  end

  def get_distance(location)
    response = BaiduMap.routematrix(location, "#{self.latitude},#{self.longitude}")
    if response["status"] == 0
      response["result"]["distance"]
    else
      { "text": "获取失败", "value": "0" }
    end
  end
    
end
